/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.uhk.ppro.response.web;

import cz.uhk.ppro.response.model.Student;
import cz.uhk.ppro.response.service.DatabaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;

/**
 *
 * @author Martin Zmítko <martin.zmitko@gmail.com>
 */

@Controller
@RequestMapping("student.do")
@SessionAttributes("student")
public class StudentFormController {

    @Autowired
    private DatabaseService databaseSession;

    @RequestMapping(method=RequestMethod.POST)
    public String onSubmit(@RequestParam(value="id",required=false) Integer id, @ModelAttribute("student") Student command) {

        if (id != null) {
            databaseSession.upravStudenta(command);
            return "redirect:/student.do?id=" + id;

        } else {
            databaseSession.pridejStudenta(command);
            return "redirect:/pupils.do";
        }

    }



    @RequestMapping(method=RequestMethod.GET)
    protected String setupForm(@RequestParam(value="id",required=false) Integer id, Model m)
    {
        if (id!=null) {
            m.addAttribute("student", databaseSession.getStudentById(id));
        } else {
            m.addAttribute("student", new Student());
        }
        return "formStudent";
    }

}
